<?php namespace Poscms\Home;
/**
 * POSCMS框架文件
 * 二次开发时请勿修改本文件
 * 四川迅睿云软件开发有限公司 www.xunruicms.com
 */

class Form extends \M_Controller {

	public $form;
    protected $field;
    protected $uriprefix;
	
    /**
     * 构造函数（网站表单）
     */
    public function __construct() {
        parent::__construct();
		$name = str_replace('form_', '', $this->router->class);
        // 表单参数为数字时按id读取
        $this->form = is_numeric($name) ? $this->get_cache('form-'.SITE_ID, $name) : $this->get_cache('form-name-'.SITE_ID, $name);
        if (!$this->form) {
            exit($this->call_msg(fc_lang('表单[%s]缓存不存在', $name)));
		}
        \Poscms\Service::M('form');
    }



	/**
     * 前端查看内容
     */
	public function show() {

        $id = (int)$this->input->get('id');
        $table = $this->form_model->prefix.'_'.$this->form['table'];

        // 获取表单数据
        $data = $this->form_model->get_data($id, $table);
        !$data && $this->msg(fc_lang('表单内容不存在'));

        $tpl = dr_tpl_path('form_'.$this->form['table'].'_show.html');
        $this->template->assign($data);
        $this->template->assign(array(
            'form' => $this->form,
            'meta_title' => $this->form['name'].SITE_SEOJOIN.SITE_NAME
        ));
        $this->template->display(is_file($tpl) ? basename($tpl) : 'form_show.html');
	}

	/**
     * 前端表单列表
     */
	public function Page() {

        $tpl = dr_tpl_path('form_'.$this->form['table'].'_page.html');
        $page = max(1, intval($_GET['page']));

        $this->template->assign(array(
            'page' => $page,
            'form' => $this->form,
            'table' => $this->form_model->prefix.'_'.$this->form['table'],
            'form_table' => $this->form['table'],
            'form_url' => 'index.php?s=form&c='.$this->form['table'].'&m=show&id=',
            'urlrule' => 'index.php?s=form&c='.$this->form['table'].'&m=page&page=[page]',
            'meta_title' => ($page > 1 ? fc_lang('第%s页', $page).SITE_SEOJOIN : '').$this->form['name'].SITE_SEOJOIN.SITE_NAME
        ));
        $this->template->display(is_file($tpl) ? basename($tpl) : 'form_page.html');
	}
	
	/**
     * 前端提交内容
     */
    protected function _post() {

		!$this->form['setting']['post'] && (IS_POST ? exit($this->call_msg(fc_lang('此表单没有开启前端提交功能'))) : $this->msg(fc_lang('此表单没有开启前端提交功能')));

		if (IS_POST) {

			$this->form['setting']['code'] && !$this->check_captcha('code') && exit($this->call_msg(fc_lang('验证码不正确')));
            
			$data = $this->validate_filter($this->form['field']);
				
			// 验证出错信息
			isset($data['error']) && exit($this->call_msg($data['msg']));

            $data[1]['uid'] =$data[0]['uid'] = $this->uid;
			$data[1]['author'] = $this->uid ? $this->member['username'] : 'guest';
			$data[1]['inputip'] = $this->input->ip_address();
			$data[1]['inputtime'] = SYS_TIME;
			$data[1]['displayorder'] = 0;

			$data[1]['id'] = $id = $this->form_model->new_addc($this->form['table'], $data);
			
			if ($this->form['setting']['send'] && $this->form['setting']['template']) {
				// 兼容php5.5
				if (version_compare(PHP_VERSION, '5.5.0') >= 0) {
                    $rep = new \php5replace($data[1]+$data[0]);
					$content = preg_replace_callback('#{(.*)}#U', array($rep, 'php55_replace_data'), $this->form['setting']['template']);
                    $content = preg_replace_callback('#{([a-z_0-9]+)\((.*)\)}#Ui', array($rep, 'php55_replace_function'), $content);
                    unset($rep);
                } else {
                    @extract($data[1]+$data[0]);
					$content = preg_replace("/{(.*)}/Ue", "\$\\1", $this->form['setting']['template']);
                    $content = preg_replace('#{([a-z_0-9]+)\((.*)\)}#Uie', "\\1(dr_safe_replace('\\2'))", $content);
				}
				$this->sendmail_queue($this->form['setting']['send'], fc_lang('【%s】通知 [来自：'.SITE_NAME.']', $this->form['name']), nl2br($content));
			}

			$this->call_msg(fc_lang('操作成功'), 1, $data);
		} else {
            $tpl = dr_tpl_path('form_'.$this->form['table'].'.html');
			$this->template->assign(array(
				'form' => $this->form,
				'code' => $this->form['setting']['code'],
				'myfield' => $this->field_input($this->form['field']),
				'meta_title' => $this->form['name'].SITE_SEOJOIN.SITE_NAME
			));
			$this->template->display(is_file($tpl) ? basename($tpl) : 'form.html');
		}
    }
	
	/**
     * 回调方法 有问题
     */
	public function call_msg($msg, $code = 0, $data = array()) {

        $url = $this->form['setting']['rt_url'];
		!$url && $url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

        IS_CMF_AJAX && $this->_json($code, $msg, array('url' => $url, 'field' => $data['error']));

        IS_API_AUTH && exit($this->callback_json(array(
            'error' => $msg,
            'code' => $code,
            'url' => $url,
        )));
		
		if (IS_AJAX) {
			exit(dr_json($code, $msg, $url)); // AJAX请求时返回json格式
		} else {
			if ($code) {
				$this->msg($msg, $url, 1); // 成功
			} else {
				$this->msg($msg); // 错误
			}
		}
	}
	
}